package com.example.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity // Spring Boot项目可以省略该注解
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
//                .requestMatchers("/user/list").hasAuthority("USER_LIST")
//                .requestMatchers("/user/add").hasAuthority("USER_ADD")
                .requestMatchers("/user/**").hasRole("ADMIN")
                .anyRequest()
                .authenticated()
        );

        http.formLogin(form -> form
                .loginPage("/login")
                .permitAll()
                .usernameParameter("my-username")
                .passwordParameter("my-password")
                .failureUrl("/login?error")
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler())
        );

        http.logout(logout -> logout.logoutSuccessHandler(new MyLogoutSuccessHandler()));

        http.exceptionHandling(exception -> exception
                .authenticationEntryPoint(new MyAuthenticationEntryPoint())
                .accessDeniedHandler(new MyAccessDeniedHandler())
        );

        http.sessionManagement(session -> session
                .maximumSessions(1)
                .expiredSessionStrategy(new MySessionInformationExpiredStrategy()));

        http.cors(withDefaults());

        http.csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withDefaultPasswordEncoder().username("chenquanchi").password("password").roles("USER").build());
//        return manager;
//    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        return new DBUserDetailsManager();
//    }
}
